package com.up4years.controller.weixin;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.up4years.controller.base.BaseController;
import com.up4years.dataapi.entity.weixin.OAuth2AccessToken;
import com.up4years.dataapi.service.weixin.WeixinMenuService;
import com.up4years.dataapi.service.weixin.WeixinMessageService;
import com.up4years.dataapi.service.weixin.WeixinService;
import com.up4years.utils.CheckUtil;
@Controller
@RequestMapping("/weixin")
public class WeixinEnterController extends BaseController {
	@Autowired
	private WeixinMenuService weixinMenuService;
	
	@RequestMapping("/home.htm")
	public String initData(Model model, HttpServletRequest request) {
  		return "/weixin/index";
	}
	/**
	 * 微信接入
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/auth.htm", method = RequestMethod.GET )
	public void auth(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		ServletResponse resp = (ServletResponse)response;
		PrintWriter out = resp.getWriter();
		//验证signature 验证通过则原样返回echostr 否则无返回
		if(CheckUtil.checkSignature(signature, timestamp, nonce)){
			out.print(echostr);
		}
	}
	@RequestMapping(value = "/getOauth2Token.htm", method = RequestMethod.GET )
	public void getOauth2Token(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String code = request.getParameter("code");
		OAuth2AccessToken token = WeixinService.getOAuth20AccessToken(code);
		JSONObject json = JSONObject.fromObject(token);
		ServletResponse resp = (ServletResponse)response;
		PrintWriter out = resp.getWriter();
		out.print(json.toString());
 	}
	@RequestMapping("/jump.htm")
	public String jump(HttpServletRequest request, HttpServletResponse response){
		return "/weixin/jump";
	}
	@RequestMapping("/test.htm")
	public String test(HttpServletRequest request, HttpServletResponse response){
		return "/weixin/test";
	}
	/**
	 * 处理微信的事件
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/auth.htm", method = RequestMethod.POST)
	public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ServletResponse resp = (ServletResponse)response;
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		try {
			Map<String, String> map = WeixinMessageService.xmlToMap(request);
			String fromUserName = map.get("FromUserName");
			String toUserName = map.get("ToUserName");
			String msgType = map.get("MsgType");
			String content = map.get("Content");
			String message = null;
			if(WeixinMessageService.MsgType_TEXT.equals(msgType)){//判断消息类型为普通消息
				message = WeixinMessageService.initText(toUserName, fromUserName, "我知道你发送的内容是："+content);
 			}else if(WeixinMessageService.MsgType_EVNET.equals(msgType)){//判断消息为事件推送
				String eventType = map.get("Event");
				if(WeixinMessageService.MsgType_SUBSCRIBE.equals(eventType)){
					message = WeixinMessageService.initText(toUserName, fromUserName, "我知道你关注我了");
				}else if(WeixinMessageService.MsgType_CLICK.equals(eventType)){
					message = WeixinMessageService.initText(toUserName, fromUserName, "我知道你在点菜单拉消息");
				}else if(WeixinMessageService.MsgType_VIEW.equals(eventType)){
					String url = map.get("EventKey");
					message = WeixinMessageService.initText(toUserName, fromUserName, "我知道你在跳转连接"+url);
				}else if(WeixinMessageService.MsgType_SCANCODE.equals(eventType)){
					String key = map.get("EventKey");
					message = WeixinMessageService.initText(toUserName, fromUserName, key);
				}
			}else if(WeixinMessageService.MsgType_LOCATION.equals(msgType)){//判断消息为地理位置消息
				String label = map.get("Label");
				message = WeixinMessageService.initText(toUserName, fromUserName, "我知道你在"+label);
			}			
			out.print(message);
		} catch (DocumentException e) {
			e.printStackTrace();
		}finally{
			out.close();
		}
	}
	@RequestMapping("/init.htm")
	@ResponseBody
	public boolean initMenus(HttpServletRequest request){
  		boolean ok = this.weixinMenuService.createMenus(request);
 		return ok;
	}
}
